<script setup lang="ts">
import { useLayoutStore } from '@/stores/layout'
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { logoutApi } from '@/api/auth'
import { ElNotification } from 'element-plus'
import { useMenuStore } from '@/stores/menu'
import { useRouter } from 'vue-router'
import type { TabMenu } from '@/type/Menu'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import ThemeToggle from '@/components/ThemeToggle.vue'

const router = useRouter()
const layoutStore = useLayoutStore()
const { userInfo, clearAuth } = useAuthStore()
const menuStore = useMenuStore()

const side = computed<boolean>(() => layoutStore.side)

const selected = computed<string|null>(() => menuStore.currentMenu)
const tabList = computed<TabMenu[]>(() => menuStore.tab || [])

// 计算右侧按钮是否应该禁用
const isRightButtonDisabled = computed(() => {
  if (!tabContainerRef.value) return true
  const container = tabContainerRef.value
  return scrollLeft.value >= container.scrollWidth - container.clientWidth - 5 // 添加5px容差
})

// 拖拽相关状态
const dragItem = ref<number | null>(null)
const dragOverItem = ref<number | null>(null)

// 滚动相关状态
const scrollLeft = ref(0)
const tabContainerRef = ref<HTMLElement | null>(null)
const showScrollButtons = ref(false)

// 检查是否需要显示滚动按钮
function checkScrollButtons() {
  if (!tabContainerRef.value) return
  const container = tabContainerRef.value
  showScrollButtons.value = container.scrollWidth > container.clientWidth
}

function changeSide() {
  layoutStore.setSide(!side.value)
}

function test() {
  menuStore.setCurrentMenu('home')
}

function doRoute(path: string) {
  router.push(path)
}

function closeTab(id: string) {
  const currentIndex = tabList.value.findIndex(tab => tab.innerId === id)
  const isCurrentTab = id === selected.value
  
  menuStore.closeTab(id)
  
  if (isCurrentTab) {
    // 找到上一个或下一个可用的标签页
    let targetTab: TabMenu | null = null
    
    // 先尝试找前一个标签页
    if (currentIndex > 0) {
      targetTab = tabList.value[currentIndex - 1]
    }
    // 如果前面没有，尝试找后一个标签页
    else if (tabList.value.length > 0) {
      targetTab = tabList.value[0]
    }
    
    // 如果有可用的标签页，跳转到该标签页
    if (targetTab) {
      router.push(targetTab.path)
    } else {
      // 如果没有其他标签页，跳转到首页
      router.push('/')
    }
  }
}

function doLogout() {
  logoutApi().then(() => {
    router.push({ path: '/home' })
    clearAuth()
    menuStore.resetMenu()
    ElNotification.success({
      title: '退出登录',
      message: '成功',
      type: 'success'
    })
  })
}

// 拖拽相关函数
function onDragStart(index: number, event: DragEvent) {
  console.log('Drag start:', index)
  dragItem.value = index
  event.dataTransfer!.effectAllowed = 'move'
}

function onDragOver(index: number, event: DragEvent) {
  event.preventDefault()
  event.dataTransfer!.dropEffect = 'move'
  if (dragItem.value !== null && dragItem.value !== index) {
    dragOverItem.value = index
  }
}

function onDrop(index: number, event: DragEvent) {
  event.preventDefault()
  if (dragItem.value !== null && dragItem.value !== index) {
    const newTabList = [...tabList.value]
    const draggedItem = newTabList[dragItem.value]
    newTabList.splice(dragItem.value, 1)
    newTabList.splice(index, 0, draggedItem)
    
    menuStore.reorderTabs(newTabList)
  }
}

function onDragEnd() {
  dragItem.value = null
  dragOverItem.value = null
}

// 滚动相关函数
function scrollTabs(direction: 'left' | 'right') {
  if (!tabContainerRef.value) return
  
  const container = tabContainerRef.value
  const scrollAmount = 200 // 每次滚动的距离
  
  if (direction === 'left') {
    container.scrollLeft -= scrollAmount
  } else {
    container.scrollLeft += scrollAmount
  }
  
  scrollLeft.value = container.scrollLeft
  // 滚动后检查按钮状态
  setTimeout(checkScrollButtons, 100)
}

function updateScrollPosition() {
  if (tabContainerRef.value) {
    scrollLeft.value = tabContainerRef.value.scrollLeft
    checkScrollButtons()
  }
}

onMounted(() => {
  checkScrollButtons()
  window.addEventListener('resize', checkScrollButtons)
  
  // 监听标签变化
  const observer = new MutationObserver(checkScrollButtons)
  if (tabContainerRef.value) {
    observer.observe(tabContainerRef.value, { childList: true, subtree: true })
  }
  
  // 清理observer
  onUnmounted(() => {
    observer.disconnect()
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScrollButtons)
})
</script>

<template>
  <div class="s-top">
    <div class="s-status">
      <div class="s-left">
        <el-icon @click="changeSide" class="icon" color="#3a3b3e" size="26">
          <Expand v-if="!side" />
          <Fold v-else />
        </el-icon>
      </div>
      <div class="s-right">
        <ThemeToggle />
        <el-dropdown>
          <div class="s-user">
            <el-avatar class="s-avatar" :size="40" :src="userInfo.avatar" />
            <h5>{{ userInfo.nickname }}</h5>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="a">个人中心</el-dropdown-item>
              <el-dropdown-item command="b" @click="test">账号安全</el-dropdown-item>
              <el-dropdown-item command="e" @click="doLogout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="s-tab-container">
      <el-button
        v-if="showScrollButtons"
        class="scroll-btn"
        :disabled="scrollLeft <= 0"
        @click="scrollTabs('left')"
        size="small"
        :icon="ArrowLeft"
      />
      
      <div
        class="s-tab"
        ref="tabContainerRef"
        @scroll="updateScrollPosition"
      >
        <div class="s-tab-item-wrapper" draggable="false">
          <el-tag
            @click="doRoute('/')"
            class="s-tab-item"
            size="large"
            :type="selected === 'home' ? 'primary' : ''"
            :effect="selected === 'home' ? 'dark' : 'plain'"
            :class="{ 'unselected-tab': selected !== 'home' }"
          >
            <div>
              <el-icon class="tab-icon">
                <House />
              </el-icon>
              <span>首页</span>
            </div>
          </el-tag>
        </div>
        <div
          v-for="(it, index) in tabList"
          :key="it.innerId"
          class="s-tab-item-wrapper"
          @dragstart="onDragStart(index, $event)"
          @dragover="onDragOver(index, $event)"
          @drop="onDrop(index, $event)"
          @dragend="onDragEnd"
        >
          <el-tag
            @click="doRoute(it.path)"
            @close="closeTab(it.innerId)"
            class="s-tab-item"
            size="large"
            closable
            :type="selected === it.innerId ? 'primary' : ''"
            :effect="selected === it.innerId ? 'dark' : 'plain'"
            :class="{ 
              'unselected-tab': selected !== it.innerId,
              'drag-over': dragOverItem === index && dragItem !== index
            }"
            :style="{ 
              opacity: dragItem === index ? 0.5 : 1
            }"
          >
            <div>
              <el-icon class="tab-icon">
                <component :is="it.menu.icon" />
              </el-icon>
              <span>{{ it.menu.menuName }}</span>
            </div>
          </el-tag>
        </div>
      </div>
      
      <el-button
        v-if="showScrollButtons"
        class="scroll-btn"
        :disabled="isRightButtonDisabled"
        @click="scrollTabs('right')"
        size="small"
        :icon="ArrowRight"
      />
    </div>
  </div>
</template>

<style scoped>
.s-top {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.s-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  box-shadow: 1px 0 2px 0 gray;
  padding: 0 15px;
}

.s-left {
  display: flex;
  align-items: center;
}

.s-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.s-top .icon {
  cursor: pointer;
  padding: 10px;
  border-radius: 50%;
  transition: 0.3s;
  margin-left: 3px;
}

.s-top .icon:hover {
  background: rgba(0, 0, 0, 0.1);
}

.s-tab-container {
  display: flex;
  align-items: center;
  height: 40px;
  border-bottom: 1px solid #eee;
  padding: 0 5px;
}

.scroll-btn {
  margin: 0 5px;
  min-width: 24px;
  height: 24px;
  padding: 0;
}

.s-tab {
  display: flex;
  align-items: center;
  overflow-x: auto;
  overflow-y: hidden;
  scroll-behavior: smooth;
  flex: 1;
  height: 100%;
  padding: 0 5px;
}

.s-tab::-webkit-scrollbar {
  display: none;
}

.s-tab {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.s-tab .s-tab-item {
  border-radius: 0;
  cursor: pointer;
  flex-shrink: 0;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.s-tab .s-tab-item.unselected-tab {
  border: 1px solid #dcdfe6 !important;
  background-color: #ffffff !important;
  color: #606266 !important;
}

.s-tab .s-tab-item div {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.s-tab .s-tab-item div .tab-icon {
  margin-right: 3px;
  flex-shrink: 0;
}

.s-tab-item-wrapper {
  display: inline-block;
  margin-right: 3px;
  user-select: none;
  -webkit-user-drag: element;
}

.s-tab .s-tab-item.drag-over {
  border: 1px dashed var(--el-color-primary) !important;
  background-color: var(--el-color-primary-light-9) !important;
  transition: all 0.2s ease !important;
}

.s-user {
  margin-right: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.s-avatar {
  margin-right: 5px;
}
</style>